// @ts-nocheck
import {createRouter, createWebHistory} from "vue-router";
import {AdminRouter} from "@/config/router/admin";
import LoginRouter from "@/config/router/login";
import useAdminLayoutStore from "@/store/admin/layout/AdminLayoutStore.ts";
import Router from "@/common/Router.ts";
import {ElMessage} from "element-plus";

const router = createRouter({
    history: createWebHistory(import.meta.env.VITE_BASE_URL),
    routes: [
        ...AdminRouter,
        ...LoginRouter,
        // 所有未定义路由，全部重定向到404页，必须放在最后, 404 页面的路由在 BasicRouter 里面
        {
            path: '/:path(.*)',
            redirect: '/404'
        },
    ]
})

export const getLocalString = (title: string): string => {
    if (title.includes(".")) {
        return t(title);
    }
    return title;
}

router.beforeEach((to, from, next) => {
    let title = to.meta.title as string ?? "Jenson"
    document.title = getLocalString(title)
    const pathBlackList = [
        '/admin'
    ]
    const token = localStorage.getItem("token")
    const isBlack = pathBlackList.some(item => to.path.startsWith(item))
    if (!token && isBlack) {
        let targetPageName = (to.meta?.title) ?? to.path;
        ElMessage.error('未登录不能访问 ' + targetPageName)
        next('/login')
    } else {
        if (isBlack) {
            const store = useAdminLayoutStore()
            let routerList: Array<Router> = []
            store.ergodicRouter(to.matched, routerList);
            store.routerToItem(routerList[1], store.getRouterItem())
            store.setRouterItemList(store.itemToList(store.getRouterItem(), []))
        }
        next()
    }
})

router.afterEach(function (to, from, next) {

})
export default router;